import React, { useEffect } from 'react';
import { Button, Select, Space } from 'antd';
import moment from 'moment';

import { TjGreenSelect } from '@/pages/ETrade/components';
import { useTRState } from '#/utils/trHooks.jsx';
import { UploadOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts.js';

import styles from './index.less';
import { queryParamConfig } from '../../services';
import { filter_dict } from '../../constant';
import { getFilterList } from '../../helper';

const Header = ({ power, initValues, loading, onChange = () => {}, onExport = () => {} }) => {
  const [state, setState] = useTRState({
    selectInfo: '筛选条件',
    showModal: false,
    originFilterList: [],
    filterList: [],
    exportTable: [],
    canExport: false,
    stationlist: [],
    params: initValues,
    loading: true,
  });

  useEffect(() => {
    init();
  }, []);

  const init = async () => {
    await fetch();
    _onFinish();
  };

  const fetch = async () => {
    setState({ loading: true });
    let { stationlist, filterList } = getFilterList(power, initValues);
    // 查询
    const res = await queryParamConfig();
    if (res.statusCode === HttpCode.SUCCESS) {
      for (var key in res.data) {
        let obj = {
          label: key,
          list: res.data[key],
          value: [...(initValues?.[filter_dict[key]] ?? [])],
        };
        if (obj.list?.length === obj.value?.length) {
          obj.allSelect = true;
        }
        filterList.push(obj);
      }
    }
    state.stationlist = stationlist;
    setState({ stationlist, loading: false, originFilterList: filterList });
    getfilterInfo(filterList);
  };

  const _onFinish = () => {
    // 查询
    const { startMonth, endMonth, ...arg } = state.params;
    const params = {
      ...arg,
      startMonth: startMonth ? moment(startMonth).format('YYYY-MM-DD') : undefined,
      endMonth: endMonth ? moment(endMonth).format('YYYY-MM-DD') : undefined,
    };
    onChange?.(params);
  };

  const _onReset = () => {
    // 重置
    let params = {
      stationIds: [],
    };
    state.params = params;
    setState({
      params,
      filterList: state.originFilterList,
      selectInfo: '筛选条件',
    });
    onChange?.(params);
  };

  const getfilterInfo = async (list) => {
    let selectInfo = [];
    let params = {
      stationIds: [],
    };
    list.map((item) => {
      if (!!item.value && item.value.length > 0) {
        let text = '';
        if (
          item.label == '场站' &&
          item.value.length > 0 &&
          item.value.length !== state.stationlist.length
        ) {
          state.stationlist.map((x) => {
            if (item.value.includes(x.label)) {
              params.stationIds.push(x.value);
            }
          });
        } else if (item.label == '日期') {
          if (item.value?.[0] && item.value?.[1]) {
            text = `日期=${item.value[0]}-${item.value[1]}`;
            params.startMonth = item.value[0];
            params.endMonth = item.value[1];
          }
        } else {
          text = `${item.label}=${item.allSelect ? '全部' : item.value.join(',')}`;
          if (!item.allSelect) {
            if (['电源类型', '环境类型', '补贴类型'].includes(item.label)) {
              params[filter_dict[item.label]] = item.value;
            } else {
              params[filter_dict[item.label]] = item.value[0];
            }
          } else {
            params[filter_dict[item.label]] = undefined;
          }
        }
        if (text != '') {
          selectInfo.push(text);
        }
      }
    });
    state.params = params;
    setState({
      showModal: false,
      filterList: list,
      selectInfo: selectInfo.length > 0 ? selectInfo : '筛选条件',
      params,
    });
  };

  const onDeselect = (data) => {
    const temp = data.split('=');
    if (!temp?.[1]) return;
    const k = temp[0];
    const v = temp[1];
    const list = filterList.map((t) => {
      let { value } = t;
      if (t.label == k) {
        if (k === '日期') {
          return {
            ...t,
            value: [],
            moments: null,
          };
        } else {
          // value = value.filter((i) => i != v);
          value = [];
          return {
            ...t,
            value,
            allSelect: false,
          };
        }
      }
      return t;
    });
    getfilterInfo(list);
  };

  const { filterList } = state;
  return (
    <div className={styles.header}>
      <Space size={16}>
        <Select
          mode={state.selectInfo !== '筛选条件' ? 'multiple' : ''}
          className={styles.moreSelect}
          value={state.selectInfo}
          open={false}
          onDeselect={onDeselect}
          onClick={() => {
            setState({ showModal: true });
          }}
        />
        <Button
          style={{ minWidth: 60, height: 32 }}
          loading={state.loading || loading}
          type="primary"
          onClick={_onFinish}
        >
          查询
        </Button>
        <Button
          style={{ minWidth: 60, height: 32 }}
          loading={state.loading || loading}
          ghost
          onClick={_onReset}
        >
          重置
        </Button>
        <TjGreenSelect
          visible={state.showModal}
          filterList={state.filterList}
          onClose={getfilterInfo}
        />
      </Space>

      <Button style={{ padding: 0 }} type="link" icon={<UploadOutlined />} onClick={onExport}>
        导出
      </Button>
    </div>
  );
};
export default Header;
